<template>
  <div class="version-manage-page">
    <div class="btns-fun-field">
      <el-button type="primary" @click.prevent="showAddEditDialog" :icon="Plus">
        新增版本信息
      </el-button>
    </div>
    <div class="">
      <el-table :data="tableData" stripe style="width: 100%" v-loading="tableLoading" border>
        <el-table-column prop="platformName" label="应用平台" width="190" />
        <el-table-column prop="platformTypeName" label="应用类型" width="110">
        </el-table-column>
        <el-table-column prop="upgradeVersion" label="版本号" width="80">
        </el-table-column>
        <el-table-column prop="upgradeVersion" label="是否线上版本" width="120">
          <template #default="scope">
            <el-tag  v-if="scope.row.isCur==1 " >线上版本</el-tag>
            <span v-else>--</span>
          </template>
        </el-table-column>
        <el-table-column prop="averageDay" label="提醒频率（天数）" width="140">
        </el-table-column>
        <el-table-column prop="noticeNum" label="提醒次数" width="90">
        </el-table-column>
        <el-table-column prop="upgradeContent" label="更新内容" width="240">
          <template #default="scope">
            <div style="width: 200px;overflow: hidden;text-overflow:ellipsis;white-space: nowrap;">{{
              scope.row.upgradeContent }}</div>
          </template>
        </el-table-column>
        <el-table-column prop="downloadUrl" label="下载链接" width="200">
          <template #default="scope">
            <div style="width: 200px;overflow: hidden;text-overflow:ellipsis;white-space: nowrap;">{{
              scope.row.downloadUrl }}</div>
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="创建时间" width="180" />
        <el-table-column label="操作" min-width="280px" fixed="right">
          <template #default="scope">
            <el-button type="primary" size="small" @click.prevent="getVersionDetail(scope.row)">查看详情</el-button>
            <el-button type="primary" size="small" @click.prevent="requestCurVersion(scope.row)">设置为线上版本</el-button>
            <el-button type="danger" size="small" @click.prevent="showRemoveDialog(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <div class="pagination-field">
        <el-pagination v-model:current-page="formData.pageIndex" v-model:page-size="formData.pageSize"
          :page-sizes="[10, 20, 30, 40]" :background="true" layout="total, sizes, prev, pager, next, jumper"
          :total="formData.total" @size-change="handleSizeChange" @current-change="handleCurrentChange" />
      </div>
    </div>


    <el-dialog v-if="removeDialogVisible" v-model="removeDialogVisible" title="删除版本信息" width="400px">
      <div style="color: #f00">确定要删除当前版本信息？</div>
      <template #footer>
        <span class="dialog-footer">
          <el-button type="default" @click="removeDialogVisible = false">取消</el-button>
          <el-button type="danger" @click="startremoveVersionInfo"> 确定 </el-button>
        </span>
      </template>
    </el-dialog>


    <el-dialog v-if="addDialogVisible" v-model="addDialogVisible" :title="addEditForm.title" width="750px">
      <div style="padding-right: 50px">
        <el-form :model="addEditForm" :rules="addEditRules" ref="addEditRef" :label-width="120">
          <el-form-item label="平台名称" prop="platformName">
            <el-input readonly v-model="addEditForm.platformName" autocomplete="off" placeholder="请输入平台名称" />
          </el-form-item>
          <el-form-item label="平台类型" prop="platformType">
            <el-select v-model="addEditForm.platformType" placeholder="选择设备类型" style="width: 100%;">
              <el-option v-for="option in platformTypeList" :key="option.id" :label="option.name" :value="option.id" />
            </el-select>
          </el-form-item>
          <el-form-item label="版本号" prop="upgradeVersion">
            <el-input v-model="addEditForm.upgradeVersion" autocomplete="off" placeholder="请输入版本号，格式为：xx.xx.xx" />
          </el-form-item>
          <el-form-item label="下载链接" prop="downloadUrl">
            <el-input v-model="addEditForm.downloadUrl" autocomplete="off" placeholder="设置新版本下载链接" />
          </el-form-item>
          <el-form-item label="提醒频率(天)" prop="averageDay">
            <el-input type="number" v-model="addEditForm.averageDay" autocomplete="off"
              placeholder="输入提醒频率(单位为天),只允许整数" />
          </el-form-item>
          <el-form-item label="提醒次数" prop="noticeNum">
            <el-input type="number" v-model="addEditForm.noticeNum" autocomplete="off" placeholder="输入提醒次数，只允许整数" />
          </el-form-item>
          <el-form-item label="更新内容" prop="upgradeContent">
            <Tinymce v-model="addEditForm.upgradeContent" style="width: 100%" :height="350"></Tinymce>
          </el-form-item>
        </el-form>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="addDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="requestAddVersionInfo"> 确定 </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>
<script setup lang="ts">
import { onMounted, reactive, ref } from 'vue';
import { Plus } from "@element-plus/icons-vue";
import { getVersionPagination, addVersionInfo, removeVersionInfo, setVersionIsCur } from "@/api/system-manage.api";
import { ElMessage } from "element-plus";
import { useRouter } from 'vue-router';
const $router = useRouter();

const formData = reactive({
  pageIndex: 1,
  pageSize: 10,
  total: 0
})

const tableLoading = ref(false);
const tableData = ref([]);
const addDialogVisible = ref(false);
const curSelectRow = ref({
  id: ''
});
const removeDialogVisible = ref(false);
const showRemoveDialog = (item: any) => {
  removeDialogVisible.value = true;
  curSelectRow.value = item;
  console.log("item: ", item);
};

const startremoveVersionInfo = () => {
  let id = curSelectRow.value.id;
  removeVersionInfo([id])
    .then(() => {
      console.log("success~~~~~");
      removeDialogVisible.value = false;
      ElMessage({
        message: "版本信息删除成功",
        type: "success",
      });
      getDataList();
    })
    .catch((err) => {
      removeDialogVisible.value = false;
      ElMessage({
        message: err.msg || err,
        type: "error",
      });
    });
};


const platformTypeList = [
  {
    id: "0",
    name: "android",
    value: 0
  },
  {
    id: "1",
    name: "ios",
    value: 1
  },
  {
    id: "2",
    name: "小程序",
    value: 2
  },
  {
    id: "3",
    name: "管理系统",
    value: 3
  },
  {
    id: "4",
    name: "java后台",
    value: 4
  }
]

const addEditRules = reactive({
  platformName: [
    { required: true, message: "请输入名称", trigger: "blur" },
    { min: 1, max: 30, message: "长度为1~30位", trigger: "blur" },
  ],
  platformType: [
    { required: true, message: "选择设备类型", trigger: "blur" },
  ],
  upgradeVersion: [
    { required: true, message: "请输入版本号，格式为：xx.xx.xx", trigger: "blur" },
  ],
  downloadUrl: [
    { required: true, message: "请输入下载链接", trigger: "blur" },
  ],
  averageDay: [
    { required: true, message: "请输入提醒频率(单位为天),只允许整数", trigger: "blur" },
  ],
  noticeNum: [
    { required: true, message: "请输入提醒次数，只允许整数", trigger: "blur" },
  ],
  upgradeContent: [
    { required: true, message: "请输入本次版本更新内容", trigger: "blur" },
  ],
});

const addEditForm = reactive({
  title: '',
  //平台名
  platformName: '袋鼠医生健康管理平台',
  //版本号
  upgradeVersion: '',
  //更新内容
  upgradeContent: '',
  //下载链接
  downloadUrl: '',
  //平台类型
  platformType: '',
  //提醒频率(天数)
  averageDay: '',
  //提醒次数
  noticeNum: '',
});

const showAddEditDialog = () => {
  addEditForm.title = "新增版本信息";
  addDialogVisible.value = true;
  addEditForm.platformName = '袋鼠医生健康管理平台';
  addEditForm.platformType = '';
  addEditForm.upgradeVersion = '';
  addEditForm.downloadUrl = '';
  addEditForm.averageDay = '';
  addEditForm.noticeNum = '';
  addEditForm.upgradeContent = ''
};


const addEditRef = ref();
const requestAddVersionInfo = () => {

  let upgradeVersion = addEditForm.upgradeVersion;
  if (!/\d{1,3}\.\d{1,3}\.\d{1,3}/.test(upgradeVersion)) {
    ElMessage({
      message: "版本号格式错误，应该为 xx.xx.xx, xx为1~3位数字",
      type: 'error'
    })
    return;
  }
  let formData = {
    platformName: addEditForm.platformName,
    platformType: addEditForm.platformType,
    upgradeVersion: addEditForm.upgradeVersion,
    downloadUrl: addEditForm.downloadUrl,
    averageDay: addEditForm.averageDay,
    noticeNum: addEditForm.noticeNum,
    upgradeContent: addEditForm.upgradeContent
  }

  if (!addEditRef.value) return;
  addEditRef.value.validate((valid: any) => {
    if (!valid) {
      return;
    }
    addVersionInfo(formData).then(() => {
      ElMessage({
        type: 'success',
        message: "新增版本信息成功"
      })
      addDialogVisible.value = false;
      getDataList();
    }).catch(err => {
      ElMessage({
        type: 'error',
        message: "新增版本失败" || err.msg || err
      });
      addDialogVisible.value = false;
    });
  });

}


const handleSizeChange = (value: number) => {
  console.log("handleSizeChange...", value)
  formData.pageSize = value;
  getDataList();

}

const handleCurrentChange = (value: number) => {
  console.log("handleCurrentChange...", value)
  formData.pageIndex = value;
  getDataList();
}


const getDataList = () => {
  tableLoading.value = true;
  getVersionPagination({
    pageSize: formData.pageSize,
    pageIndex: formData.pageIndex
  }).then(function (res: any) {
    tableLoading.value = false;
    console.log(res)
    let list = res.list || [];
    list = list.map((item: any) => {

      let platformTypeItem = platformTypeList.find(row => {
        return row.value == item.platformType;
      });
      if (platformTypeItem) {
        item.platformTypeName = platformTypeItem.name
      }
      return item;
    });
    tableData.value = res.list || []
    formData.total = Number(res.total);
    formData.pageIndex = Number(res.pageIndex);
    formData.pageSize = Number(res.pageSize);
  }).catch(error => {
    console.log(error)
    tableLoading.value = false;
  })
}


onMounted(() => {
  getDataList();
})


const getVersionDetail = (item: any) => {
  $router.push({
    path: `/system/version/detail`,
    query: {
      platformType: item.platformType
    }
  });
}

const requestCurVersion = (item: any)=>{
  
  let formData = {
    id: item.id,
    platformType: item.platformType
  }
  setVersionIsCur( formData ).then( ()=>{
    ElMessage({
      type: "success",
      message: "设置线上版本成功"
    })
    getDataList();
  }).catch( (err:any)=>{
      ElMessage({
        type: "error",
        message: err.msg || err || "操作失败"
      })
  } )
}

</script>
<style lang="scss" scoped>
.btns-fun-field {
  margin-bottom: 20px;
}

.pagination-field {
  display: flex;
  justify-content: flex-end;
  margin: 20px 0;
}

.version-manage-page {
  padding: 20px;
  background-color: #fff;
}
</style>
  